/* eslint-disable import/first */
/* eslint-disable react-hooks/rules-of-hooks */
/*
 * @Author: your name
 * @Date: 2021-10-11 21:00:32
 * @LastEditTime: 2021-11-10 21:01:11
 * @LastEditors: Shentong
 * @Description: 我的收藏
 * @FilePath: /distribution/src/pages/collect/index.tsx
 */
// eslint-disable-next-line @typescript-eslint/no-use-before-define
import React, { useEffect, useState, useReducer, useCallback, useRef  } from 'react';
import Taro, { useDidShow, usePullDownRefresh, useReachBottom } from '@tarojs/taro';
import { View } from "@tarojs/components";

import styles from './index.module.scss'

import { userAPIAuthSeting } from '@/utils/index'

import ProdItem from '@/src/components/custom/prodItem';

import { getCollectList } from '@/api/collect'

import NoDataIcon from '@/src/assets/icon/noDataIcon.png'
import NoMore from "@/components/custom/no-more";

const listReducer = (state, action) => {
    switch (action.type) {
        case 'init': return action.payload
        case 'concat': return state.concat(action.payload)
        default: return state
    }
}

const collect = () => {
    const [pageNo, setPageNo] = useState(1);
    const [pageSize] = useState(10);

    const [showSkeleton, setShowSkeleton] = useState<boolean>(true)

    const [collectList, localDispatch] = useReducer(listReducer, [])
    const [isLoadFinish, setIsloadFinish] = useState(false)

    // 经纬度
    const [locationInfo, setLocationInfo] = useState({lon: 0, lat: 0})
    const showSkeletonRef =  useRef(true);

    const dataList = useCallback(() => {
      if (!locationInfo.lon || !locationInfo.lat) return

      if(!showSkeletonRef.current) Taro.showLoading({ title: "加载中...", mask: true });

      const params = Object.assign(locationInfo, { pageSize, pageNo})
      getCollectList(params).then(res => {
          const { data: { records = [], lastPage } = {} } = res
          setIsloadFinish(lastPage)
          const actionType = pageNo === 1 ? 'init' : 'concat'

          localDispatch({ type: actionType, payload: records })

          Taro.hideLoading();
      }).finally(() => {
          setShowSkeleton(false)
          showSkeletonRef.current = false
          Taro.stopPullDownRefresh();
      })
    }, [localDispatch, pageNo, pageSize, locationInfo])

    const getLocation = () => {
      userAPIAuthSeting('scope.userLocation',{},() => {
        Taro.getLocation({
          type: 'gcj02', //返回可以用于 Taro.openLocation的经纬度
          success: function (res) {
            const { latitude: lat, longitude:lon } = res
            console.log('getLocation-res', lat, lon )
            // TODO:
            setLocationInfo({ lat, lon })
            // setLocationInfo({lon: 121.59129211429878, lat: 38.91349631790786})
          }
        })
      })
     }

     // 点击进入商品详情页
   const shopItemClick = (item) => {
    Taro.navigateTo({
     url: `/pages/detail/index?shopId=${item.shopSId}`
   })
  }

   // 下拉刷新
    usePullDownRefresh(() => {
      if (pageNo !== 1)  setPageNo(1);
      else dataList()
    });
    useReachBottom(() => {
        !isLoadFinish && setPageNo(pageNo + 1)
    })

    useDidShow(() => {
      getLocation()
    })

    useEffect(() => {
      dataList()
    }, [dataList])

    return (
        <View className={styles.collect}>
            <View>
                {
                    collectList.map((item, index) => {
                      return (<ProdItem
                        shop={item}
                        key={`shop_${index}`}
                        clickHandle={() => { shopItemClick(item) }}
                      />)

                    })
                }
                {collectList.length && isLoadFinish ? <NoMore /> : null}
            </View>

            {
                !showSkeleton && !collectList.length && (
                    <van-empty description='暂无数据' image={NoDataIcon} />
                )
            }

        </View>
    )
}

export default collect
